package com.jinbiao.quasar.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.hash.Hash;
import cn.hutool.json.JSONUtil;
import com.jinbiao.quasar.annotate.OperationLog;
import com.jinbiao.quasar.dto.MenuDto;
import com.jinbiao.quasar.dto.OnlineUserDto;
import com.jinbiao.quasar.model.SysButton;
import com.jinbiao.quasar.model.SysMenu;
import com.jinbiao.quasar.util.AjaxJson;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.data.annotation.Tran;
import org.noear.solon.extend.sqltoy.annotation.Db;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.sagacity.sqltoy.model.EntityQuery;
import org.sagacity.sqltoy.model.Page;

import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
@OperationLog
public class MenuController {
    @Db
    SqlToyLazyDao dao;
    @Mapping("/menu/get-menu-list")
    public AjaxJson getMenuList(int page,int pageSize) {
        Page<MenuDto> pageResult =  dao.findPageBySql(new Page(pageSize,page),"sysMenuList",new HashMap<>(),MenuDto.class);
        pageResult.getRows().stream().forEach(item->{
            List<SysButton> buttons = dao.findBySql("sysButtonList",new SysButton(item.getName()));
            item.setButton(buttons);
        });
        return AjaxJson.getSuccessData(pageResult);
    }

    @Mapping("/menu/delete-menu-by-id")
    public AjaxJson deleteMenuById(SysMenu sysMenu){
        return AjaxJson.getSuccessData(dao.delete(sysMenu));
    }

    @Mapping("/menu/edit-menu")
    public AjaxJson editMenu(SysMenu sysMenu){
        return AjaxJson.getSuccessData(dao.saveOrUpdate(sysMenu));
    }

    @Mapping("/menu/edit-button")
    @Tran
    public AjaxJson editButton(MenuDto menuDto){
        dao.deleteByQuery(SysButton.class,EntityQuery.create().where("menu_name=?").values(menuDto.getName()));
        return AjaxJson.getSuccessData(dao.saveAll(menuDto.getButton()));
    }

    @Mapping("/menu/add-menu")
    public AjaxJson addMenu(SysMenu sysMenu){
        return AjaxJson.getSuccessData(dao.saveOrUpdate(sysMenu));
    }

    @Mapping("/menu/query-menu-by-id")
    public AjaxJson queryMenuById(SysMenu sysMenu){
        List<SysMenu> results = dao.findBySql("sysMenuList",sysMenu);
        if(CollectionUtil.isNotEmpty(results)){
            SysMenu menu = results.get(0);
            MenuDto menuDto = new MenuDto();
            BeanUtil.copyProperties(menu,menuDto,false);
            List<SysButton> buttons = dao.findBySql("sysButtonList",new SysButton(menu.getName()));
            menuDto.setButton(buttons);
            return AjaxJson.getSuccessData(menuDto);
        }
        return AjaxJson.getSuccessData(null);
    }

}
